#include "adduser.h"
#include "ui_adduser.h"
#include "string"
#include "QMessageBox"
#include "adminmanager.h"
#include <QCryptographicHash>
#include "../MainProject/sqlitedatabase.h"
#include "../MainProject/loggermanager.h"
addUser::addUser(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::addUser),firstwindow(nullptr)
{
    ui->setupUi(this);
    window()->setWindowTitle("添加新用户");
}


void addUser::setFirstWindow(AdminManager *firstWindow)
{

    this->firstwindow = firstWindow;

}

QString addUser::hashPassword(const QString &password)
{
    // 创建一个 QCryptographicHash 对象，设置其使用 MD5 算法
    QCryptographicHash hasher(QCryptographicHash::Md5);

    // 添加密码数据到哈希对象中（注意：转为 QByteArray）
    hasher.addData(password.toUtf8());

    // 计算哈希值并获取结果，转换为十六进制格式字符串
    QString hashedPassword = hasher.result().toHex();

    return hashedPassword;
}

bool addUser::validateEmail(const QString &email)
{
    QRegularExpression regex(R"((^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$))");
    return regex.match(email).hasMatch();
}

bool addUser::validatePhoneNumber(const QString &phoneNumber)
{
    QRegularExpression regex(R"(^1[3-9]\d{9}$)");
    return regex.match(phoneNumber).hasMatch();
}


addUser::~addUser()
{
    delete ui;
}

void addUser::on_saveButton_clicked()
{   QString password;
    QString userName= ui->userNameEdit->text();
    QString passwords= ui->passwordEdit->text();
    password=hashPassword(passwords);
    QString email =ui->EmailEdit->text();
    QString phone=  ui->phoneEdit->text();
    // QString role = ui->comboBox->currentText();
    m_nPermission = ui->comboBox->currentIndex();
    bool phoneflag=true;
    bool emailfalg=true;
    if(userName.isEmpty()){
        QMessageBox::information(this, "waring", "用户名不能为空");
       // Logger().logError("用户名输入为空");
        return;
    }
    else {
        // 校验名字
    }

    if(passwords.isEmpty()){
        QMessageBox::information(this, "waring", "密码不能为空");
       //  Logger().logError("密码输入为空");

        return;
    }

    if(email.isEmpty()){
        QMessageBox::information(this, "waring", "邮箱不能为空");
      //   Logger().logError("邮箱输入为空");
        return;
    }
    else {
        if (!validateEmail(email)) {
            QMessageBox::information(this, "waring", "邮箱格式错误，请输入正确的邮箱地址");
        //      Logger().logError("邮箱地址格式输入错误");
            ui->EmailEdit->clear();
            return;
        }
        else {
            //查询手机号
            SQLiteDatabase* db = SQLiteDatabase::getInstance();
            QString condition = QString("email = '%1'").arg(email); // 设置条件字符串
            QJsonArray result = db->read("users", condition); // 调用read方法获取结果
            // for (const QJsonValue& value : result) {
            //     QJsonObject obj = value.toObject();
            //     qDebug() << "User:" << obj;
            // }
            if(!result.isEmpty()){
                QMessageBox::information(this, "waring","该邮箱已存在已存在");
         //        Logger().logError("输入的邮箱已存在");
                emailfalg=false;
            }
        }
    }

    if(phone.isEmpty()){
        QMessageBox::information(this, "waring", "手机号不能为空");
      //    Logger().logError("手机号输入为空");
        return ;
    }
    else {
        if (!validatePhoneNumber(phone)) {
            QMessageBox::information(this, "waring", "手机号格式错误，请输入正确的手机号");
         //      Logger().logError("手机号格式输入错误");
            return;
        }
        else {
            //查询用户名
            SQLiteDatabase* db = SQLiteDatabase::getInstance();
            QString condition = QString("phone = '%1'").arg(phone); // 设置条件字符串
            QJsonArray result = db->read("users", condition); // 调用read方法获取结果
            // for (const QJsonValue& value : result) {
            //     QJsonObject obj = value.toObject();
            //     qDebug() << "User:" << obj;
            // }
            if(!result.isEmpty()){
                QMessageBox::information(this, "waring","该手机号已存在");
           //      Logger().logError("输入的手机号已存在");
                phoneflag=false;
            }
        }
    }

    if(m_nPermission == ADMIN) {
        m_strPermission = "admin";
    }
    else if (m_nPermission == USER) {
        m_strPermission = "user";
    }

    if(!userName.isEmpty()&&!passwords.isEmpty()&&!email.isEmpty()&&!phone.isEmpty()&& phoneflag && emailfalg){
        SQLiteDatabase* db = SQLiteDatabase::getInstance();

        // 创建记录
        QJsonObject user;
        user["username"] = userName;
        user["password"] = password;
        user["email"] = email;
        user["phone"] = phone;
        user["role"] = m_strPermission;
        db->create("users", user);
        //添加成功,
        QMessageBox::information(this, "success", "添加成功");
       // Logger().logInfo("用户添加成功");

        //隐藏自己
        //SQLiteDatabase* db = SQLiteDatabase::getInstance();
        QJsonArray result = db->read("users", "");


        firstwindow->selectAllUsers(result);
        this->hide();
    }
}


